<template>
	<div>

		<div class="btn-wrap">
			<el-button type="primary" size="small" icon="el-icon-plus" @click="addAttr(false)">添加属性</el-button>
		</div>
		<el-table v-loading="loading" :data="attrs" row-key="sortNo" :tree-props="{ children: 'values' }">
			<el-table-column prop="name" label="属性名称"></el-table-column>
			<el-table-column label="操作" align="center">
				<template slot-scope="scope">
					<el-button v-if="scope.row.values" type="text" size="small" icon="el-icon-plus" @click="addAttr(scope.row)">添加值</el-button>
					<el-button type="text" size="small" icon="el-icon-edit-outline" @click="editAttr(scope.row)">编辑</el-button>
					<el-button type="text" size="small" icon="el-icon-delete" @click="deleteAttr(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

	</div>
</template>

<script>
	export default {
		data() {
			return {
				attrs: [],
				loading: false
			}
		},
		created() {
			this.findAttrs();
		},
		methods: {
			findAttrs() {
				this.loading = true;
				this.$util.request('/sku/findAttrs', {}, (res) => {
					this.loading = false;

					let count = 0;
					this.attrs = res.map(e => {
						count++;
						e.sortNo = count;
						e.values.forEach(v => {
							count++;
							v.sortNo = count;
						});
						return e;
					});
				}, true);
			},
			addAttr(item) {
				this.$prompt('输入属性' + (item ? '值' : '名称'), '添加属性' + (item ? '值' : '名称'), {
					inputValidator(val) {
						if (!val) return '请输入名称';
					}
				}).then(res => {
					const loading = this.$loading({
						text: '处理中...'
					});
					this.$util.request('/sku/' + (item ? 'saveValue' : 'saveAttr'), {
						name: res.value,
						keyId: item ? item.id : ''
					}, (res) => {
						loading.close();
						if (res.state == 'ok') {
							this.$message.success('添加成功');
							this.findAttrs();
						} else {
							this.$util.msg(res.msg);
						}
					});
				}).catch(_ => {});
			},
			editAttr(item) {
				this.$prompt('输入属性' + (item.values ? '值' : '名称'), '更新属性' + (item.values ? '值' : '名称'), {
					inputValue: item.name,
					inputValidator(val) {
						if (!val) return '请输入名称';
					}
				}).then(res => {
					const loading = this.$loading({
						text: '处理中...'
					});
					this.$util.request('/sku/' + (item.values ? 'updateAttr' : 'updateValue'), {
						name: res.value,
						id: item.id
					}, (res) => {
						loading.close();
						if (res.state == 'ok') {
							this.$message.success('更新成功');
							this.findAttrs();
						} else {
							this.$util.msg(res.msg);
						}
					});
				}).catch(_ => {});
			},
			deleteAttr(item) {
				this.$util.requestWithConfirm('确定删除吗？', '/sku/' + (item.values ? 'deleteAttr' : 'deleteValue'), {
					id: item.id
				}, '警告').then(_ => {
					this.findAttrs();
				}, '', '删除');
			}
		}
	};
</script>

<style lang="scss">
	.btn-wrap {
		margin-bottom: 20px;
	}
</style>
